import pymysql
from pymysql.err import OperationalError, IntegrityError
# 移除加密相关导入
# from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
# from cryptography.hazmat.primitives import hashes
# from cryptography.hazmat.backends import default_backend
# import base64
from config import DB_CONFIG  # 不再导入加密配置

class DBUtil:
    @staticmethod
    def get_connection():
        """获取数据库连接（不变）"""
        try:
            conn = pymysql.connect(**DB_CONFIG)
            return conn
        except OperationalError as e:
            print(f"数据库连接失败：{e}")
            return None

    @staticmethod
    def hash_password(password: str) -> str:
        """简化：直接返回明文密码（不加密）"""
        return password

    @staticmethod
    def verify_password(password: str, stored_password: str) -> bool:
        """简化：直接对比明文密码"""
        try:
            return password == stored_password
        except Exception as e:
            print(f"密码验证失败：{e}")
            return False

    @staticmethod
    def query_user(username: str) -> dict:
        """查询用户（不变，返回明文密码）"""
        conn = None
        try:
            conn = DBUtil.get_connection()
            if not conn:
                return None
            cursor = conn.cursor(pymysql.cursors.DictCursor)
            sql = "SELECT * FROM `user` WHERE `username` = %s AND `is_active` = 1"
            cursor.execute(sql, (username,))
            user = cursor.fetchone()
            return user
        except Exception as e:
            print(f"查询用户失败：{e}")
            return None
        finally:
            if conn:
                conn.close()

    @staticmethod
    def register_user(username: str, password: str, email: str) -> bool:
        """注册用户：直接存储明文密码"""
        conn = None
        try:
            conn = DBUtil.get_connection()
            if not conn:
                return False
            cursor = conn.cursor()
            sql = """
                INSERT INTO `user` (`username`, `password_hash`, `role`, `email`)
                VALUES (%s, %s, 'normal', %s)
            """
            # 直接存入明文密码（password参数已是明文）
            cursor.execute(sql, (username, password, email))
            conn.commit()
            print(f"新用户注册成功：用户名={username}，密码={password}（明文存储）")
            return True
        except IntegrityError as e:
            print(f"注册失败：用户名或邮箱已存在 - {e}")
            if conn:
                conn.rollback()
            return False
        except Exception as e:
            print(f"注册失败：{e}")
            if conn:
                conn.rollback()
            return False
        finally:
            if conn:
                conn.close()

    @staticmethod
    def update_last_login(user_id: int) -> bool:
        """更新登录时间（不变）"""
        conn = None
        try:
            conn = DBUtil.get_connection()
            if not conn:
                return False
            cursor = conn.cursor()
            sql = "UPDATE `user` SET `last_login_time` = CURRENT_TIMESTAMP WHERE `user_id` = %s"
            cursor.execute(sql, (user_id,))
            conn.commit()
            return True
        except Exception as e:
            print(f"更新登录时间失败：{e}")
            if conn:
                conn.rollback()
            return False